<template>
  <div class="questions">
    <h2 class="page-content">试题管理</h2>
    <div class="actions mb-3">
      <button @click="addQuestion()" class="btn btn-primary">
        <i class="fas fa-plus"></i> 添加试题
      </button>
      <select v-model="selectedBank" @change="loadQuestions" class="select-bank">
        <option value="">所有题库</option>
        <option v-for="bank in questionBanks" :key="bank.id" :value="bank.id">
          {{ bank.name }}
        </option>
      </select>
      <div class="search-box">
        <input v-model="searchQuery" @input="searchQuestions" placeholder="搜索试题..." />
        <i class="fas fa-search"></i>
      </div>
    </div>

    <div class="table-responsive">
      <table class="test-table">
        <thead>
          <tr>
            <th>题目</th>
            <th>类型</th>
            <th>难度</th>
            <th>题库</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="question in filteredQuestions" :key="question.id" @mouseover="hover = question.id"
            @mouseleave="hover = null" >
            <td style="max-width: 400px;">
              <div class="question-content" @click="toggleQuestionDetails(question)">
                <div style="width: 100%; display: flex; flex-direction: column;justify-content: center;">
                  <div v-html="renderMath(question.content)"></div>
              <div style="max-width: 100% ;  display: flex; flex-direction: column;justify-content: center;">
              <img style="max-width: 200px; max-height: 100px; border-radius: 10px;" v-if="question.image" :src="question.image" alt="">
              </div>
                </div>

                <i :class="['fas', question.showDetails ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
              </div>
              <transition name="fade">
              <div v-if="question.showDetails" class="question-details">
                <div v-if="question.answerVoList && question.answerVoList.length > 0">
                  <div>
                    <p><strong>选项：</strong></p>
                    <ul class="options-list">
                      <li v-for="(option, index) in question.answerVoList" :key="index"
                        :class="{ 'correct-option': option.isCorrect }" style="border: 1px solid var(--border);">
                        <div style="display: flex; gap: 10px;">   {{ option.abc }}. <div v-html="renderMath(option.content)"></div></div>
                        <div v-if="question.correctAnswerVo">
                          <span v-if="question.correctAnswerVo.optionIds.includes(option.id)" class="correct-badge">
                          <i class="fas fa-check"></i> 正确答案
                        </span></div>

                      </li>
                    </ul>
                  </div>
                </div>
                <div style=" max-width: 100%;">
                  <div v-if="question.analysis" style=" max-width: 100%;"><strong>答案:</strong>&nbsp;&nbsp;
                    <div v-html="sanitizedHtml(question.analysis)"></div>
                  </div>
                  <p v-else><strong>答案:</strong>&nbsp;&nbsp;无</p>
                </div>
              </div>
            </transition>
            </td>
            <td><span :class="getTypeClass(question.quTypeDictText)">{{ question.quTypeDictText }}</span></td>
            <td><span :class="getDifficultyClass(question.difficulty)">{{ question.difficulty }}</span></td>
            <td>{{ getBankName(question.bankId) }}</td>
            <td style="display: flex;justify-content: center; gap: 5px; flex-wrap: wrap;">
              <button @click="editQuestion(question)" class="action-button">
                <i class="fas fa-edit"></i> 编辑
              </button>
              <button @click="deleteQuestion(question.id)" class="action-button">
                <i class="fas fa-trash"></i> 删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>





    <div class="table-container">

  </div>




  <Pagination
      :totalItems="totalPages"
      :itemsPerPage="pageSize"
      :initialPage="1"
      @page-change="handlePageChange"
    />
    <Loading
      :size="60"
      color="#4CAF50"
      shadowColor="#A5D6A7"
      :speed="0.6"
      :loading="loading"
      backgroundColor="rgba(255, 255, 255, 0.8)">
</Loading>

    <!-- Add/Edit Modal -->
    <div >
      <Dialog v-model="editingQuestionShow" title="试题编辑" width="1000px" @close="handleClose">
        <div >
          <EditQuestion    :questionForm="questionForm" />
        </div>
      </Dialog>
      <Dialog v-model="addQuestionShow" title="添加题目" width="1305px" @close="handleClose">
        <div >
          <AddQuestion  @addShow="handleShow"  v-if="addQuestionShow" />
        </div>
      </Dialog>
  </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { api } from '../../api/mockApi';
import { QuestionService } from '@/api/questionApi';
import Dialog from '@/components/commont/Dialog.vue';
import EditQuestion from '@/components/exam/questions/edit/EditQuestion.vue';
import AddQuestion from '@/components/exam/questions/add/AddQuestion.vue';
import Pagination from '@/components/commont/Pagination.vue';
import Loading from '@/components/commont/Loading.vue';

import DOMPurify from 'dompurify';
import katex from 'katex';
import 'katex/dist/katex.min.css';

const renderMath = (text) => {
  if (!text) return '';
  // 匹配行内公式 $...$
  let result = text.replace(/\$(.*?)\$/g, (_, m) =>
    katex.renderToString(m.trim(), {
      throwOnError: false,
      strict: false
    }));

  // 匹配块级公式 $$...$$
  result = result.replace(/\\$\$(.*?)\\$\$/gs, (_, m) =>
    katex.renderToString(m.trim(), {
      displayMode: true,
      throwOnError: false,
      strict: false
    }));

  return result;
};

const sanitizedHtml = ((html) => {
  return DOMPurify.sanitize(html)
});


const loading=ref(false);
const questions = ref([]);
const questionBanks = ref([]);
const showModal = ref(false);
const editingQuestion = ref(null);
const searchQuery = ref('');
const selectedBank = ref('');
const currentPage = ref(1);
const pageSize = ref(8);
const totalPages=ref(1);
const editingQuestionShow = ref(false);
const addQuestionShow = ref(false);



const defaultQuestionForm = {
  content: '',
  type: '单选题',
  difficulty: '中等',
  bankId: '',
  answer: '',
  options: []
};



const handleShow = (data) => {
  console.log(data)
  addQuestionShow.value = data;
};
const questionForm = ref({ ...defaultQuestionForm });

onMounted(async () => {
  await loadQuestionBanks();
  await loadQuestions(currentPage.value);
});

const loadQuestionBanks = async () => {
  questionBanks.value = await api.getQuestionBanks();
};
const handleClose=()=>{
  editingQuestionShow.value=false;
  addQuestionShow.value=false;
}
const loadQuestions = async (page) => {
  loading.value=true
try{  const response = await QuestionService.getQuestion({
    page: page,
    size: pageSize.value
  });
  totalPages.value=response.map.totalPage;
  currentPage.value=response.map.currentPage;
  questions.value = response.data;}
  finally{
    setTimeout(()=>{
      loading.value=false
    },300)
  }

};
const  handlePageChange = (pageData)=>{
  currentPage.value = pageData.page;
  loadQuestions(currentPage.value);
 console.log(pageData)
};

const getBankName = (bankId) => {
  const bank = questionBanks.value.find(b => b.id === bankId);
  return bank ? bank.name : 'Unknown';
};


const editQuestion = (question) => {
  editingQuestion.value = question;
  questionForm.value = {
    ...question,
    options: question.answerVoList ? [...question.answerVoList] : []
  };


console.log("questionForm.value",questionForm.value)

  showModal.value = true;
  editingQuestionShow.value=true
};

const addQuestion=()=> {
  addQuestionShow.value=true
  showModal.value = true;
};
const deleteQuestion = async (id) => {
  if (confirm('确定要删除这个试题吗？')) {
    await api.deleteQuestion(id);
    await loadQuestions();
  }
};

const saveQuestion = async () => {
  console.log(questionForm.value)
};

const toggleQuestionDetails = (question) => {
  question.showDetails = !question.showDetails;
};

const getTypeClass = (type) => {
  switch (type) {
    case '单选题': return 'type-single';
    case '多选题': return 'type-multiple';
    case '判断题': return 'type-judge';
    case '填空题': return 'type-fill';
    default: return '';
  }
};

const getDifficultyClass = (difficulty) => {
  switch (difficulty) {
    case '简单': return 'difficulty-easy';
    case '中等': return 'difficulty-medium';
    case '困难': return 'difficulty-hard';
    default: return '';
  }
};

const filteredQuestions = computed(() => {
  return questions.value.filter(question =>
    question.content.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    question.quTypeDictText.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});
</script>


<style scoped lang="scss">
.questions {
  padding: 2rem;
  animation: slide-out-right 0.2s ease-in-out forwards;
  height: 100%;
}

@keyframes slide-out-right {
  0% {
    transform: translateX(100%);
    opacity: 0;
  }

  0% {
    transform: translateX(50%);
    opacity: 0.5;
  }

  100% {
    transform: translateX(0);
    opacity: 1;
  }

}

.page-content {
  font-size: 2rem;
  margin-bottom: 1.5rem;
  color: var(--primary-color);
}

.actions {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.select-bank,
.search-box input {
  padding: 0.75rem;
  border-radius: 4px;
  font-size: 1rem;
  border: 1px solid var(--border-color);
}

.search-box {
  position: relative;
  max-width: 300px;
}

.search-box input {
  padding-left: 2rem;
}

.search-box i {
  position: absolute;
  left: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: #6c757d;
}

.table-responsive {
  width: 100%;
  overflow-x: auto;
  background-color: #f5f7fa;
  padding: 16px;

}
.test-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  border-radius: 4px;
  overflow: hidden;
}



.test-table th {
  background-color: #f5f7fa;
  padding: 12px 16px;
  text-align: left;
  font-weight: 500;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
}

.test-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
}
.question-content {
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  color: var(--primary-color);
}

.question-details {
  margin-top: 0.75rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;

}

.options-list {
  list-style: none;
  padding: 0;
  margin: 1rem 0;
  max-width: 100%;
}
.action-button {
  background-color: var(--button-color);
  color: var(--text);
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}
.options-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 1rem;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin: 0.3rem 0;

}

.correct-option {
  color: #52c41a;
}

.correct-badge {
  background-color: #e6f7e6;
  color: #52c41a;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
}

.option-item {
  margin-bottom: 1rem;
  padding: 1rem;
  border-radius: 6px;
  background-color: #fafafa;
  border: 1px solid #ddd;
}

.option-content {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 1rem;
  align-items: center;
}

.option-label {
  font-weight: bold;
}

.option-text {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s ease; /* 渐隐渐现效果 */
}

.fade-enter-from, .fade-leave-to {
  opacity: 0; /* 初始状态和结束状态 */
}
/* 新增样式 */
</style>
